﻿using Core.Core;
using Core.Modal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace www.api
{
    /// <summary>
    /// ProjectHandler 的摘要说明
    /// </summary>
    public class ProjectHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            try {
                string func = context.Request["function_type"].ToString();
                switch (func) {
                    case "addProject":
                        addProject(context);
                        break;
                    case "delProject":
                        delProject(context);
                        break;
                }
            }
            catch (Exception ex) {
                context.Response.Write(new ResponseData("400", ex.Message.ToString(),"").ToString());
            }
        }

        /// <summary>
        /// 删除项目
        /// </summary>
        /// <param name="context"></param>
        private void delProject(HttpContext context)
        {
            string project_id = context.Request["project"]?.ToString();
            ProjectUtil.Delete(Convert.ToInt32(project_id));
            context.Response.Write(new ResponseData("200", "项目删除成功", "").ToString());
        }

        /// <summary>
        /// 新建项目
        /// </summary>
        /// <param name="context"></param>
        private void addProject(HttpContext context)
        {
            string project_id = context.Request["id"]?.ToString();
            string name = context.Request["name"]?.ToString();
            string comment = context.Request["comment"]?.ToString();
            if (project_id == "0") {
                project_id = ProjectUtil.Add(name, comment).ToString();
            }
            else {
                ProjectUtil.Update(Convert.ToInt32(project_id), name, comment);
            }            

            if (project_id != "-1")
            {
                context.Response.Write(new ResponseData("200", "项目保存成功", project_id).ToString());
            }
            else {
                context.Response.Write(new ResponseData("400", "项目保存失败","").ToString());
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}